<template>
  <div class="saleBusiness components-container">
  <el-form :inline="true" :model="policySearch" class="demo-form-inline">
      <el-col :span="20">
        <el-form-item label="汽车品牌">
          <el-input v-model="policySearch.brandName"   :clearable="true" placeholder="请输入汽车品牌"></el-input>
        </el-form-item>
        <el-form-item label="型号规格">
          <el-input v-model="policySearch.modelName"   :clearable="true" placeholder="请输入型号规格"></el-input>
        </el-form-item>
        <el-form-item label="销售方式">
          <el-select v-model="saleTypeSearchTmp" multiple clearable placeholder="可多选" @change="saleTypeSearchChange()">
          <el-option
            v-for="item in saleTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryPolicy" size="medium" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-col>
      <el-col :span="4" style="text-align:right;"><el-button type="primary" size="medium" icon="el-icon-plus" @click="policyDialog('add')" v-show="showAdd">新增</el-button></el-col>
  </el-form>
       <template>
        <el-table
          v-loading="loading"
          :data="tableData"
          class="fns-table"
          border
          style="width: 100%">
          <el-table-column
            prop="policyCode"
            align="center"
            label="政策编号"  min-width="140">
          </el-table-column>
          <el-table-column
            prop="brandName"
            align="center"
            label="汽车品牌" >
          </el-table-column>
          <el-table-column
            prop="modelName"
            align="center"
            label="型号规格">
          </el-table-column>
          <el-table-column
            prop="stockNum"
            align="center"
            label="库存总数" min-width="60">
          </el-table-column>
          <el-table-column 
            prop="saleType"
            align="center"
            label="销售方式" :formatter="saleTypeFormatter" min-width="80">
          </el-table-column>
          <el-table-column
            prop="retailUnitPrice"
            align="center"
            label="零售单价(万元)" min-width="90">
          </el-table-column>
          <el-table-column
            prop="batchUnitPrice"
            align="center"
            label="批售单价(万元)" min-width="90">
          </el-table-column>
          <el-table-column
            prop="guidePrice"
            align="center"
            label="指导价(万元)" min-width="90">
          </el-table-column>
         <!--  <el-table-column
           prop="saleArea"
           align="center"
           label="可售省份">
         </el-table-column> -->
          <el-table-column
            prop="updatedOn"
            label="修改日期"
            align="center"
            min-width="180">
          </el-table-column>
          <el-table-column
          label="操作"
          align="center"
          min-width="80">
          <template slot-scope="scope" >
            <el-tooltip content="修改" placement="top" v-show="showUpdate">
            <a @click="policyDialog('update', scope.$index, scope.row)">
              <i class="el-icon-edit-outline"></i>
            </a>
          </el-tooltip>
          </template>
        </el-table-column>

         
        </el-table>
      </template>

     <!-- ========页码======-->
    <pages v-on:_pageChange="_pageChange" :total="total"></pages>

      <el-dialog 
        title="新增商务政策" 
        :visible.sync="dialogVisible"
        width="960px"
        class="fns-el-dialog-md" 
        :before-close="handleClose" :close-on-click-modal="false" >
         <el-col :span="24" class="main">
        <el-form :inline="true"  class="demo-form-inline" label-width="150px" style="margin-left:6px;" :model="policy" :rules="rules" ref="policy">
        <el-row :gutter="5">
           <el-col :span="12" >
          <el-form-item label="汽车品牌：" prop="brandId">
            <el-select style="z-index:1" :disabled="showBrandName" v-model="policy.brandId" @change="brandChange()" filterable  placeholder="可搜索选择" clearable>
            <el-option  
              v-for="(item, index) in policyBrandOptions"
              :key="index"
              :label="item.keyName"
              :value="item.valueName">
               </el-option>
          </el-select>
        </el-form-item>
      </el-col>
          <el-col :span="12" :pull="2">
         <el-form-item label="型号规格：" prop="modelId">
            <el-select :disabled="showModelName" v-model="policy.modelId" filterable  placeholder="可搜索选择">
            <el-option
              v-for="(item, index) in modelList"
              :key="index"
              :label="item.keyName"
              :value="item.valueName">
            </el-option>
          </el-select>
          </el-form-item>
        </el-col>
      </el-row>
       <!-- <el-row :gutter="5">
           <el-col :span="10">
        <el-form-item label="库存总数：" prop="number"><span v-model="policy.number">{{policy.number}}</span></el-form-item>
             </el-col>
          </el-row> -->
   <el-row :gutter="5">
    <el-col :span="12" >
         <el-form-item label="销售方式：" prop="saleType">
           <template>
            <el-checkbox-group v-model="saleTypeTmp" @change="saleTypeChange()">
               <el-checkbox v-for="(saleType, index) in saleTypeOptions" :label="saleType.value" :key="index">{{saleType.label}}</el-checkbox>
            </el-checkbox-group>
          </template>
         </el-form-item>
         </el-col>
       <el-col :span="12" :pull="2">
         <el-form-item label="开票方式：" prop="ticketType">
           <template>
            <el-checkbox-group v-model="ticketTypeTmp" @change="ticketTypeChange()">
              <el-checkbox v-for="(ticketType, index) in ticketTypeOptions" :label="ticketType.value" :key="index">{{ticketType.label}}</el-checkbox>
            </el-checkbox-group>
          </template>
         </el-form-item>
       </el-col>
           
     </el-row >
     <el-row :gutter="5">
        <el-col :span="12">

           <el-form-item label="零售单价(万元)：" prop="retailUnitPrice">
            <el-input-number :disabled="showRetailUnitPrice" v-model="policy.retailUnitPrice" placeholder="请输入零售单价" value="number" :min="0" :max="9999999999"></el-input-number>
         </el-form-item>
       </el-col>
         <el-col :span="12" :pull="2">
         <el-form-item label="批售单价(万元)：" prop="batchUnitPrice">
            <el-input-number :disabled="showBatchUnitPrice" v-model="policy.batchUnitPrice" placeholder="请输入批售单价" value="number" :min="0" :max="9999999999"></el-input-number>
         </el-form-item>
       </el-col>
        
      </el-row>
      <el-row :gutter="5">
       
       <el-col :span="12">
          <el-form-item label="指导价(万元)：" prop="guidePrice">
            <el-input-number v-model="policy.guidePrice" placeholder="请输入指导价" value="number" :min="0" :max="9999999999"></el-input-number>
         </el-form-item>
         
        </el-col>
        <el-col :span="12" :pull="2">
        <el-form-item label="是否需要支付全款：" prop="fullPayment">
         <template>
            <el-radio-group v-model="policy.fullPayment">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
             </el-radio-group>
          </template>
        </el-form-item>
        </el-col>
    </el-row>
    <el-row :gutter="5">
        <el-col :span="24">
         <el-form-item label="批售保证金：" prop="policyMargins" >
            <template >
            <el-table
            :data="policy.policyMargins"
            border 
            class="table-height" >
            <el-table-column
            align="center"
            label="台数区间" width="250">
            <template slot-scope="scope" >
            <div style="display:block;">
              <div style="display:inline-block;"><span>{{ scope.row.minInterval }}</span></div>
              <div style="display:inline-block;"><span>-</span></div>
              <div style="display:inline-block;">
               <el-input style="width:120px":disabled="showMaxInterval" :readonly="scope.row.readonly" @blur="maxIntervalBlur(scope.row)" placeholder="最高台数" :maxlength="2" size="small" v-model="scope.row.maxInterval"  ></el-input>
              </div>
          </div>
          </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="保证金总额(万元)" width="180" >
            <template slot-scope="scope">
          <el-input-number :disabled="showTotalMargin" placeholder="所需保证金" size="small" v-model="scope.row.totalMargin" value="number" :min="0"></el-input-number>        
        </template>
          </el-table-column>
          <el-table-column
           align="center"
     
      label="操作"
      width="100">
      <template slot-scope="scope">

        <el-button @click="addPolicyMargins(scope.row)" :disabled="parseInt(scope.row.maxInterval) <= parseInt(scope.row.minInterval) || scope.$index+1 < policy.policyMargins.length || scope.row.maxInterval === '' ? true : false" type="text" size="small"  >新增</el-button>
        <el-button @click="deletePolicyMargins(scope.row, scope.$index)" v-show="showDelete(scope.$index)" type="text" size="small"  >删除</el-button>
         </template>
    </el-table-column>
            </el-table>
            </template>
          </el-form-item>
        </el-col>
   </el-row>
        <el-row :gutter="5">
          <el-col :span="24" class="modalCheckBox">
            <el-form-item label="销售省份：" prop="saleArea" class="saleArea">
              <template >
              <div v-for="(item, index) in areaOptions" :key="index">
                <div v-if="index === 0">
                  <el-checkbox :indeterminate="isIndeterminate1" v-model="checkAll1" @change="handleCheckAllChange1">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea1" @change="handleCheckedCitiesChange1">
                    <el-checkbox v-for="line1 in item.city" :label="line1" :key="line1">{{ line1 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="index === 1">
                  <el-checkbox :indeterminate="isIndeterminate2" v-model="checkAll2" @change="handleCheckAllChange2">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea2" @change="handleCheckedCitiesChange2">
                    <el-checkbox v-for="line2 in item.city" :label="line2" :key="line2">{{ line2 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
       
                <div v-if="index === 2">
                  <el-checkbox :indeterminate="isIndeterminate3" v-model="checkAll3" @change="handleCheckAllChange3">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea3" @change="handleCheckedCitiesChange3">
                    <el-checkbox v-for="line3 in item.city" :label="line3" :key="line3">{{ line3 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="index === 3">
                  <el-checkbox :indeterminate="isIndeterminate4" v-model="checkAll4" @change="handleCheckAllChange4">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea4" @change="handleCheckedCitiesChange4">
                    <el-checkbox v-for="line4 in item.city" :label="line4" :key="line4">{{ line4 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
             </template>
            </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
         <el-col :span="24">
            <el-form-item label="备注(选填)：">
              <el-input type="textarea" v-model="policy.remarks" placeholder="请填写备注" style="width:560px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
           <el-col :span="24">
            <el-form-item label="参考图片(选填)：">
              <el-upload
              class="upload-demo"
              action="uploadUrl"
               ref="upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :auto-upload="false"
              :http-request='submitUpload'
              :file-list="urlList"
              list-type="picture-card"
              multiple
              :limit="3"
              :on-exceed="handleExceed">
               <el-button slot="trigger" size="small" type="primary">选取文件</el-button> 
               <el-button style="margin-left: 10px;" size="small" type="success" @click="submitServer">上传图片</el-button>
              <div slot="tip" class="el-upload__tip" style="color:#F56C6C">只能上传jpg、jpeg、gif、png文件，且不超过5M，最多上传三张图片</div>
            </el-upload>
              
           
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </el-col>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPolicy('policy')">提 交</el-button>
        </span>
     
      </el-dialog>
            <el-dialog style="z-index:99" :visible.sync="imgDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
      <el-dialog 
        title="修改商务政策"
        :visible.sync="dialogEditVisible"
        width="960px"
      class="fns-el-dialog-md"
       :before-close="handleEditClose" :close-on-click-modal="false" >
         <el-col :span="24" class="main">
        <el-form :inline="true"  class="demo-form-inline" label-width="150px" style="margin-left:6px;" :model="policy" :rules="rules" ref="policy">
        <el-row :gutter="5">
           <el-col :span="12" >
          <el-form-item label="汽车品牌：" prop="brandId">
            <el-select :disabled="showBrandName" v-model="policy.brandId" @change="brandChange()" filterable  placeholder="可搜索选择" clearable>
            <el-option
              v-for="(item, index) in brandOptions"
              :key="index"
              :label="item.keyName"
              :value="item.valueName">
               </el-option>
          </el-select>
        </el-form-item>
      </el-col>
          <el-col :span="12" :pull="2">
         <el-form-item label="型号规格：" prop="modelId">
            <el-select :disabled="showModelName" v-model="policy.modelId" filterable  placeholder="可搜索选择">
            <el-option
              v-for="(item, index) in modelList"
              :key="index"
              :label="item.keyName"
              :value="item.valueName">
            </el-option>
          </el-select>
          </el-form-item>
        </el-col>
      </el-row>
   <el-row :gutter="5">
    <el-col :span="12" >
         <el-form-item label="销售方式：" prop="saleType">
           <template>
            <el-checkbox-group v-model="saleTypeTmp" @change="saleTypeChange()">
               <el-checkbox v-for="(saleType, index) in saleTypeOptions" :label="saleType.value" :key="index">{{saleType.label}}</el-checkbox>
            </el-checkbox-group>
          </template>
         </el-form-item>
         </el-col>
       <el-col :span="12" :pull="2">
         <el-form-item label="开票方式：" prop="ticketType">
           <template>
            <el-checkbox-group v-model="ticketTypeTmp" @change="ticketTypeChange()">
              <el-checkbox v-for="(ticketType, index) in ticketTypeOptions" :label="ticketType.value" :key="index">{{ticketType.label}}</el-checkbox>
            </el-checkbox-group>
          </template>
         </el-form-item>
       </el-col>
           
     </el-row >
     <el-row :gutter="5">
        <el-col :span="12">

           <el-form-item label="零售单价(万元)：" prop="retailUnitPrice">
            <el-input-number :disabled="showRetailUnitPrice" v-model="policy.retailUnitPrice" placeholder="请输入零售单价" value="number" :min="0" :max="9999999999"></el-input-number>
         </el-form-item>
       </el-col>
         <el-col :span="12" :pull="2">
         <el-form-item label="批售单价(万元)：" prop="batchUnitPrice">
            <el-input-number :disabled="showBatchUnitPrice" v-model="policy.batchUnitPrice" placeholder="请输入批售单价" value="number" :min="0" :max="9999999999"></el-input-number>
         </el-form-item>
       </el-col>
        
      </el-row>
      <el-row :gutter="5">
       
       <el-col :span="12">
          <el-form-item label="指导价(万元)：" prop="guidePrice">
            <el-input-number v-model="policy.guidePrice" placeholder="请输入指导价" value="number" :min="0" :max="9999999999"></el-input-number>
         </el-form-item>
         
        </el-col>
        <el-col :span="12" :pull="2">
        <el-form-item label="是否需要支付全款：" prop="fullPayment">
         <template>
            <el-radio-group v-model="policy.fullPayment">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
             </el-radio-group>
          </template>
        </el-form-item>
        </el-col>
    </el-row>
    <el-row :gutter="5">
        <el-col :span="24">
         <el-form-item label="批售保证金：" prop="policyMargins" >
            <template >
             
            <el-table
            :data="policy.policyMargins"
            border 
            class="table-height" >
          
            <el-table-column
            align="center"
            label="台数区间" width="250">
         <template slot-scope="scope" >
            <div style="display:block;">
              <div style="display:inline-block;"><span>{{ scope.row.minInterval }}</span></div>
              <div style="display:inline-block;"><span>-</span></div>
              <div style="display:inline-block;">
               <el-input style="width:120px":disabled="showMaxInterval" :readonly="scope.row.readonly" @blur="maxIntervalBlur(scope.row)" placeholder="最高台数" :maxlength="2" size="small" v-model="scope.row.maxInterval"  ></el-input>
              </div>
          </div>
          </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="保证金总额(万元)" width="180" >
            <template slot-scope="scope">
          <el-input-number :disabled="showTotalMargin" placeholder="所需保证金" size="small" v-model="scope.row.totalMargin" value="number" :min="0"></el-input-number>
           </template>
          </el-table-column>
          <el-table-column
           align="center"
     
      label="操作"
      width="100">
      <template slot-scope="scope">

        <el-button @click="addPolicyMargins(scope.row)" :disabled="parseInt(scope.row.maxInterval) <= parseInt(scope.row.minInterval) || scope.$index+1 < policy.policyMargins.length || scope.row.maxInterval === '' ? true : false" type="text" size="small"  >新增</el-button>
        <el-button @click="deletePolicyMargins(scope.row, scope.$index)" v-show="showDelete(scope.$index)" type="text" size="small"  >删除</el-button>
         </template>
    </el-table-column>
            </el-table>
            </template>
          </el-form-item>
        </el-col>
   </el-row>
        <el-row :gutter="5">
          <el-col :span="24" class="modalCheckBox">
            <el-form-item label="销售省份：" prop="saleArea" class="saleArea">
              <template >
              <div v-for="(item, index) in areaOptions" :key="index">
                <div v-if="index === 0">
                  <el-checkbox :indeterminate="isIndeterminate1" v-model="checkAll1" @change="handleCheckAllChange1">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea1" @change="handleCheckedCitiesChange1">
                    <el-checkbox v-for="line1 in item.city" :label="line1" :key="line1">{{ line1 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="index === 1">
                  <el-checkbox :indeterminate="isIndeterminate2" v-model="checkAll2" @change="handleCheckAllChange2">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea2" @change="handleCheckedCitiesChange2">
                    <el-checkbox v-for="line2 in item.city" :label="line2" :key="line2">{{ line2 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
       
                <div v-if="index === 2">
                  <el-checkbox :indeterminate="isIndeterminate3" v-model="checkAll3" @change="handleCheckAllChange3">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea3" @change="handleCheckedCitiesChange3">
                    <el-checkbox v-for="line3 in item.city" :label="line3" :key="line3">{{ line3 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="index === 3">
                  <el-checkbox :indeterminate="isIndeterminate4" v-model="checkAll4" @change="handleCheckAllChange4">{{
                    item.title }}
                  </el-checkbox>
                  <el-checkbox-group v-model="salesArea4" @change="handleCheckedCitiesChange4">
                    <el-checkbox v-for="line4 in item.city" :label="line4" :key="line4">{{ line4 }}</el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
             </template>
            </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="5">
         <el-col :span="24">
            <el-form-item label="备注(选填)：">
              <el-input type="textarea" v-model="policy.remarks" placeholder="请填写备注" style="width:560px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
           <el-col :span="24">
            <el-form-item label="参考图片(选填)：">
              <el-upload
              class="upload-demo"
              action="uploadUrl"
               ref="upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :auto-upload="false"
              :http-request='submitUpload'
              :file-list="urlList"
              list-type="picture-card"
              multiple
              :limit="3"
              :on-exceed="handleExceed">
               <el-button slot="trigger" size="small" type="primary">选取文件</el-button> 
               <el-button style="margin-left: 10px;" size="small" type="success" @click="submitServer">上传图片</el-button>
              <div slot="tip" class="el-upload__tip" style="color:#F56C6C">只能上传jpg、jpeg、gif、png文件，且不超过5M，最多上传三张图片</div>
            </el-upload>
             
           
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </el-col>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPolicy('policy')">提 交</el-button>
        </span>
     
      </el-dialog>
           <el-dialog style="z-index:99" :visible.sync="imgDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
  </div>
</template>

<script>
    import { Message } from 'element-ui'
    import pages from '../../components/page/page'
    import * as api from '@/api/system'
    import { findMenu, findSubMenu, findBtn } from '@/utils/btn'
    import { mapState, mapActions } from 'vuex'
    import qs from 'qs'
    export default {
      data() {
        return {
          isIndeterminate1: false,
          isIndeterminate2: false,
          isIndeterminate3: false,
          isIndeterminate4: false,
          cityArr1: [],
          cityArr2: [],
          cityArr3: [],
          cityArr4: [],
          checkAll1: false,
          checkAll2: false,
          checkAll3: false,
          checkAll4: false,
          salesArea1: [],
          salesArea2: [],
          salesArea3: [],
          salesArea4: [],
          saleTypeTmp: [],
          ticketTypeTmp: [],
          saleTypeSearchTmp: [],
          page: {
            index: 1,
            size: 10
          },
          total: 0,
          uploadUrl: '',
          imgDialogVisible: false,
          dialogImageUrl: '',
          minNumber: 7,
          maxNumber: 99,
          loading: false,
          modelTitle: '',
          addOrUpdate: 'add',
          dialogVisible: false,
          dialogEditVisible: false,
          showMaxInterval: true,
          showTotalMargin: true,
          showRetailUnitPrice: true,
          showBatchUnitPrice: true,
          showBrandName: false,
          showModelName: false,
          relativePath: '', 
          policySearch: {
            id: '',
            brandName: '',
            modelName: '',
            saleType: []
          },
          rules: {
            brandId: [{ required: true, message: '请选择汽车品牌', trigger: 'change' }],
            modelId: [{ required: true, message: '请选择型号规格', trigger: 'change' }],
            saleType: [{ required: true, message: '请选择销售方式', trigger: 'blur' }],
            ticketType: [{ required: true, message: '请选择开票方式', trigger: 'blur' }],
            retailUnitPrice: [{ required: true, message: '请填写零售单价', trigger: 'blur' }],
            batchUnitPrice: [{ required: true, message: '请填写批售单价', trigger: 'blur' }],
            guidePrice: [{ required: true, message: '请填写指导价', trigger: 'blur' }],
            fullPayment: [{ required: true, message: '请选择是否需要支付全款', trigger: 'change' }],
            saleArea: [{ required: true, message: '请选择销售省份', trigger: 'blur' }]
          },
          policy: {
            id: '',
            brandId: '',
            modelId: '',
            saleType: [],
            ticketType: [],
            retailUnitPrice: 0,
            batchUnitPrice: 0,
            guidePrice: 0,
            fullPayment: 0,
            saleArea: [],
            policyMargins: [
              {
                maxInterval: '',
                minInterval: 6,
                totalMargin: 0
              }
            ],
            remarks: '',
            imgUrl: []
          },
          brandList: [],
          modelList: [],
          tableData: [],
          urlList: []
        }
      },
      created() {
        if (this.$route.params.uuid) {
          this.policySearch.id = this.$route.params.uuid
          this.queryPolicy()
        } else {
          this.queryPolicy()
        }
        api.getRelativePath().then((res) => {
          this.relativePath = res.data
        })
      },
      components: {
        pages
      },
      watch: {
        dialogVisible() {
          if (this.$refs.policy) {
            this.$refs.policy.clearValidate()
          }
        }
      },
      computed: {
        ...mapState({
          areaOptions: state => state.selecteData.area,
          saleTypeOptions: state => state.selecteData.saleType,
          ticketTypeOptions: state => state.selecteData.ticketType,
          policyBrandOptions: state => state.selecteData.policyBrandOptions,
          brandOptions: state => state.selecteData.brandOptions
        }),
        showAdd() {
          let menu = findMenu('销售管理')
          let subMenu = findSubMenu(menu.children, '商务政策管理')
          if (findBtn(subMenu.children, '新增')) {
            return true
          } else {
            return false
          }
        },
        showUpdate() {
          let menu = findMenu('销售管理')
          let subMenu = findSubMenu(menu.children, '商务政策管理')
          if (findBtn(subMenu.children, '修改')) {
            return true
          } else {
            return false
          }
        }
      },
      methods: {
        maxIntervalBlur(row) {
          if (row.maxInterval > 99) {
            this.$message({
              message: '保证金最大台数不能超过两位数',
              type: 'error',
              showClose: true
            })
          } else if (row.maxInterval.indexOf('.') !== -1) {
            this.$message({
              message: '请输入整数',
              type: 'error',
              showClose: true
            })
          }
          if (parseInt(row.maxInterval) <= row.minInterval && row.maxInterval !== '') {
            this.$message({
                message: '请检查台数区间是否正确',
                type: 'error',
                showClose: true
            })
          }
        },
        submitServer() {
          this.$refs.upload.submit()
        },
        saleTypeSearchChange: function() {
          var saleTypeSearchArr = [0, 0]
          var saleTypeSearchTmp = this.saleTypeSearchTmp
          saleTypeSearchTmp.forEach((item) => {
            if(item === '0') {
              saleTypeSearchArr.splice(0, 1, 1)
            } else {
              saleTypeSearchArr.splice(1, 1, 1)
            }
          })
          this.policySearch.saleType = saleTypeSearchArr
        },
        saleTypeChange: function() {
          this.showTotalMargin = true
          this.showMaxInterval = true
          this.showRetailUnitPrice = true
          this.showBatchUnitPrice = true
          var saleTypeArr = [0, 0]
          var saleTypeTmp = this.saleTypeTmp
          if (saleTypeTmp.length === 1 && saleTypeTmp.includes('0')) {
              this.policy.batchUnitPrice = 0
          }  else if (saleTypeTmp.length === 1 && saleTypeTmp.includes('1')) {
              this.policy.retailUnitPrice = 0
          }
          saleTypeTmp.forEach((item) => {
            if(item === '0') {
              saleTypeArr.splice(0, 1, 1)
              this.showRetailUnitPrice = false
            } else {
              this.showBatchUnitPrice = false
              this.showTotalMargin = false
              this.showMaxInterval = false
              saleTypeArr.splice(1, 1, 1)
            }
          })
          this.policy.saleType = saleTypeArr
        }, 
        ticketTypeChange: function() {
          var ticketTypeArr = [0, 0, 0]
          var ticketTypeTmp = this.ticketTypeTmp
          ticketTypeTmp.forEach((item) => {
            if(item === '0') {
              ticketTypeArr.splice(0, 1, 1)
            } else if (item === '1') {
              ticketTypeArr.splice(1, 1, 1)
            } else {
              ticketTypeArr.splice(2, 1, 1)
            }
          })
          this.policy.ticketType = ticketTypeArr
        },
        changeUpload: function(file, fileList) { // 预览图片  
          this.fileList = fileList 
          this.$nextTick(  
            () => {  
              let upload_list_li = document.getElementsByClassName('el-upload-list')[0].children;  
              for (let i = 0; i < upload_list_li.length; i++) {  
                  let li_a = upload_list_li[i].children[0]  
                  let imgElement = document.createElement("img") 
                  imgElement.setAttribute('src', fileList[i].url)  
                  imgElement.setAttribute('style', "max-width:50%;padding-left:25%")  
                  if (li_a.lastElementChild.nodeName !== 'IMG') {  
                      li_a.appendChild(imgElement) 
                  }  
              }  
          })  
        },
        submitUpload: function(content) { // 自定义的上传图片的方法  
          // console.log(this.urlList)
          // 1. 创建formData 调用api传递  
          let formData = new FormData  
          formData.append('file', content.file)  
          // var data = qs.stringify(formData)
          var _this = this
          api.policyUpload(formData).then((res) => {
            if (+res.code === 0) {
              _this.$message({
                  message: res.friendlyMsg,
                  type: 'success'
              })
              var imgUrl = res.data+'/'+content.file.name
              this.policy.imgUrl.push(imgUrl)
            }
            }).catch(function(error) {  
                _this.$message({
                  message: error.friendlyMsg,
                  type: 'error'
              })  
            })  
        },    
        // 清除arr值
        clearArrVal(arr) {
          for (var Item in arr) {
            arr[Item] = ''
          }
        },
        // 获取集合
        getIntersection(val, back) {
          var a = new Set(val)
          var b = new Set(back)
          const intersectionSet = new Set([...a].filter(x => b.has(x)))
          var result = Array.from(intersectionSet)
          return result
        },
        handleRemove(file, fileList) {
          let policyImgUrl = this.policy.imgUrl
          let urlList = this.urlList
          if (policyImgUrl.length !== 0) {
            policyImgUrl.splice(policyImgUrl.findIndex(item => item.includes(file.name)), 1)
            this.policy.imgUrl = policyImgUrl
          }
          if (urlList.length !== 0) {
            urlList.splice(urlList.findIndex(item2 => item2.name === file.name), 1)
            this.urlList = urlList
          }
        },
        handlePreview(file) {
          this.dialogImageUrl = file.url
          this.imgDialogVisible = true
        },
        handleExceed(files, fileList) {
          this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        },
        beforeRemove(file, fileList) {
          return this.$confirm(`确定移除 ${ file.name }？`)
        },
        getCity() {
          this.cityArr1 = this.areaOptions[0].city
          this.cityArr2 = this.areaOptions[1].city
          this.cityArr3 = this.areaOptions[2].city
          this.cityArr4 = this.areaOptions[3].city
        },
        deletePolicyMargins(row, index) {
          // this.maxNumber = this.policy.policyMargins[index-1].minInterval + 99
          this.minNumber = this.policy.policyMargins[index-1].minInterval + 1
          this.policy.policyMargins[index-1].readonly = false
          this.policy.policyMargins.pop()
        },
        showDelete(index) {
          var rIndex = index + 1
          if (rIndex === this.policy.policyMargins.length && rIndex !== 1) {
            return true
          }
        },
        addPolicyMargins(row) {
          if (row.maxInterval - row.minInterval > 99) {
            this.$message({
                message: `保证金区间不能超过两位数`,
                type: 'error',
                showClose: true
              })
          } else {
            this.minNumber = parseInt(row.maxInterval) + 2
            // this.maxNumber = parseInt(this.minNumber) + 98
            row.readonly = true
            this.policy.policyMargins.push({ 'maxInterval': '', 'minInterval': parseInt(row.maxInterval) + 1, 'totalMargin': 0, readonly: false })
          }
        },
        brandChange() {
          this.policy.modelId = ''
          if (this.policy.brandId === '') {
            this.modelList = []
            return
          } else {
            api.allPolicyBrandModel({'id': this.policy.brandId}).then((res) => {
              this.modelList = res.data
            })
          }
        },
        saleTypeFormatter(row, column) {
          switch(row.saleType) {
            case '1,0':
            return '零售'
            break

            case '0,1':
            return '批售'
            break

            case '1,1':
            return '零售,批售'
            break
          }
        },
        policyDialog(val, index, row) {
          this.getCity()
          this.$store.dispatch('policyBrandOptions')
          if (val === 'add') {
            /*api.allPolicyBrandModel({'id': 0}).then(res => {
              this.policyBrandOptions = res.data
             // resolve()
            })*/
            for (var Item in this.policy) {
              this.policy[Item] = ''
              if (Item === 'saleType' || Item === 'ticketType' || Item === 'saleArea' || Item === 'imgUrl') {
                this.policy[Item] = []
              } else if (Item === 'policyMargins') {
                this.policy[Item] = [
                  {
                    maxInterval: '',
                    minInterval: 6,
                    totalMargin: 0,
                    readonly: false
                  }
                ]
              }
            }
            this.urlList = []
            this.modelList = []
            this.showTotalMargin = true
            this.showMaxInterval = true
            this.showBatchUnitPrice = true
            this.showRetailUnitPrice = true
            this.showBrandName = false
            this.showModelName =false
            this.minNumber = 7,
            this.maxNumber = 99,
            this.saleTypeTmp = []
            this.ticketTypeTmp = []          
            // this.policy.number = 0
            this.policy.fullPayment = 0
            this.salesArea1 = []
            this.salesArea2 = []
            this.salesArea3 = []
            this.salesArea4 = []
            this.checkAll1 = false
            this.checkAll2 = false
            this.checkAll3 = false
            this.checkAll4 = false
            this.dialogVisible = true
            this.addOrUpdate = 'add'
          } else {
            this.showBrandName = true
            this.showModelName =true
            this.showBatchUnitPrice = true
            this.showRetailUnitPrice = true
            this.getPolicy(row)
            this.addOrUpdate = 'update'
            this.dialogEditVisible = true
          }
        },
        // 回显商务政策
        getPolicy(row) {
          api.policyListById(row.id).then((res) => {
            if (+res.code === 0) {
              var rowData = res.data
              this.policy.id = parseInt(row.id)
              this.policy.brandId = String(rowData.brandId)
              this.policy.modelId = String(rowData.modelId)
              /*api.allBrand({'id': 0}).then(res => {
                this.policyBrandOptions = res.data
              })*/
              api.modelPageListNoAuth(this.policy.brandId).then((res) => {
                this.modelList = res.data
                /*let modelListTmp= res.data.rows
                let modelListTmp2 = []
                modelListTmp.forEach(item => {
                  let { id, modelName } = item
                  const item2 = { id, modelName }
                  let { id:valueName, modelName:keyName } = item2
                  const item3 = { valueName, keyName }
                  modelListTmp2.push(item3)
                })
                this.modelList = modelListTmp2*/
              })
              var area = []
              if (rowData.saleArea.indexOf(',') !== -1) {
                area = rowData.saleArea.split(',')
              } else {
                area.push(rowData.saleArea)
              }
              this.showTotalMargin = true
              this.showMaxInterval = true
              var saleStr = rowData.saleType.split(',')
              var saleStrTmp = []
              if (saleStr[0] === '1') {
                saleStrTmp.push('0')
                this.showRetailUnitPrice =false
              }
              if (saleStr[1] === '1') {
                this.showBatchUnitPrice = false
                this.showTotalMargin = false
                this.showMaxInterval = false
                saleStrTmp.push('1')
              }
              this.policy.saleType = rowData.saleType
              this.saleTypeTmp = saleStrTmp
              var ticketStr = rowData.ticketType.split(',')
              var ticketStrTmp = []
              if (ticketStr[0] === '1') {
                ticketStrTmp.push('0')
              } 
              if (ticketStr[1] === '1') {
                ticketStrTmp.push('1')
              }
              if (ticketStr[2] === '1') {
                ticketStrTmp.push('2')
              }
              this.policy.ticketType = rowData.ticketType
              this.ticketTypeTmp = ticketStrTmp
              this.policy.retailUnitPrice = rowData.retailUnitPrice || 0
              this.policy.batchUnitPrice = rowData.batchUnitPrice || 0
              this.policy.guidePrice = rowData.guidePrice || 0
              this.policy.fullPayment = rowData.fullPayment
              if (rowData.policyMargins.length === 0) {
                rowData.policyMargins.push({
                    maxInterval: '',
                    minInterval: 6,
                    totalMargin: 0
                  }) 
              } else {
                rowData.policyMargins.forEach(item => {
                 if (item.maxInterval === '99999') {
                    item.maxInterval = ''
                  }
                })
              }
              this.policy.policyMargins = rowData.policyMargins
              this.minNumber = 7,
              this.maxNumber = 99,
              
              this.policy.saleArea = area
              this.policy.remarks = rowData.remarks
              this.policy.imgUrl = [] // rowData.imgUrl
              this.urlList = []
              var urlListTmp = []
              var urlListTmp2 = []
              if (rowData.imgUrl.includes(',')) {
                var imgUrlArr = rowData.imgUrl.split(',')
                imgUrlArr.forEach((item) => {
                  this.policy.imgUrl.push(item)
                  urlListTmp = item.split('/')
                  if(urlListTmp[1].match(/\.(jpg|jpeg|png|gif)$/)) {
                    this.urlList.push({ name: urlListTmp[1], url: this.relativePath+'/'+urlListTmp[0] })
                  }
                  // console.log(this.urlList)
                })
              } else if (rowData.imgUrl !== '') {
                urlListTmp2 = rowData.imgUrl.split('/')
                if (urlListTmp2[1].match(/\.(jpg|jpeg|png|gif)$/)) {
                  this.urlList.push({ name: urlListTmp2[1], url: this.relativePath+'/'+urlListTmp2[0] })
                }
                this.policy.imgUrl.push(rowData.imgUrl)
              }
              this.salesArea1 = this.getIntersection(this.areaOptions[0].city, area)
              this.salesArea2 = this.getIntersection(this.areaOptions[1].city, area)
              this.salesArea3 = this.getIntersection(this.areaOptions[2].city, area)
              this.salesArea4 = this.getIntersection(this.areaOptions[3].city, area)
              // 销售区域
              this.checkAll1 = true
              this.checkAll2 = true
              this.checkAll3 = true
              this.checkAll4 = true
              var _this = this
              var city1 = this.areaOptions[0].city
              var city2 = this.areaOptions[1].city
              var city3 = this.areaOptions[2].city
              var city4 = this.areaOptions[3].city
              city1.forEach(function(item, index) {
                if (area.indexOf(item) === -1) {
                  _this.checkAll1 = false
                }
              })
              city2.forEach(function(item, index) {
                if (area.indexOf(item) === -1) {
                  _this.checkAll2 = false
                }
              })
              city3.forEach(function(item, index) {
                if (area.indexOf(item) === -1) {
                  _this.checkAll3 = false
                }
              })
              city4.forEach(function(item, index) {
                if (area.indexOf(item) === -1) {
                  _this.checkAll4 = false
                }
              })
            }
          })
        },
        submitPolicy(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.addOrUpdate === 'add') {
                this.addPolicy()
              } else {
                this.updatePolicy()
              }
            } else {
              return false
            }
          })
        },
        _pageChange(val, flag) {
          this.clearArrVal(this.policy)
          var arr = []
          if (flag === 'size') {
            this.page.index = val
            this.queryPolicy()
          } else {
            arr.push(val)
            this.page.index = 1
            this.page.size = arr[0]
            this.queryPolicy()
          }
        },
        queryPolicy() {
          this.loading = true
          var pages = {
            index: this.page.index,
            size: this.page.size
          }
          if (Array.isArray(this.policySearch.saleType)) {
            this.policySearch.saleType = this.policySearch.saleType.join(',')
            if (this.policySearch.saleType === '0,0') {
              delete this.policySearch.saleType
            }
          }
          var data = Object.assign(this.policySearch, pages)
          api.policyPageList(data).then((res) => {
            if (+res.code === 0) {
              this.tableData = res.data.rows
              this.total = +res.data.total
              this.policySearch.id = ''
            }
            this.loading = false
          }).catch(err => {
            console.log(err)
            this.loading = false
          })
        },
        addPolicy() {
          delete this.policy.id
          // delete this.policy.number
          if (Array.isArray(this.policy.policyMargins)) {
            this.policy.policyMargins.forEach((item) => {
              delete item.readonly
            })
          }
          // this.$refs.upload.submit() // 上传图片到服务器
          this.policy.brandId = parseInt(this.policy.brandId)
          if (Array.isArray(this.policy.saleArea)) {
            this.policy.saleArea = this.policy.saleArea.join(',')
          }
          if (Array.isArray(this.policy.ticketType)) {
            if (!this.policy.ticketType.includes(1)) {
              this.$message({
                message: '请选择开票方式',
                type: 'error'
              })
              return
            }
            this.policy.ticketType = this.policy.ticketType.join(',')
          } else {
            if (!this.policy.ticketType.includes(1)) {
              this.$message({
                message: '请选择开票方式',
                type: 'error'
              })
              return
            }
          }
          if (Array.isArray(this.policy.saleType)) {
            var saleTypeArr2 = this.policy.saleType
            if (!saleTypeArr2.includes(1)) {
              this.$message({
                message: '请选择销售方式',
                type: 'error'
              })
              return
            }
            if (saleTypeArr2[1] === 0) {
              this.policy.policyMargins = []
            }
            this.policy.saleType = this.policy.saleType.join(',')
          } else {
            if (!this.policy.saleType.includes(1)) {
              this.$message({
                message: '请选择销售方式',
                type: 'error'
              })
              return
            }
          }
          if (Array.isArray(this.policy.imgUrl)) {
            if (this.policy.imgUrl.length > 1) {
              this.policy.imgUrl = this.policy.imgUrl.join(',')
            } else if (this.policy.imgUrl.length === 1){
              this.policy.imgUrl = (this.policy.imgUrl)[0]
            } else {
              this.policy.imgUrl = ""
            }
          }
          if (this.policy.policyMargins.length !== 0) {
            this.policy.policyMargins.map((item) => {
              if (item.maxInterval !== '') {
              item.maxInterval = parseInt(item.maxInterval)
              }
              item.minInterval = parseInt(item.minInterval)
            })
          }
          api.policyAdd(this.policy).then((res) => {
            if (+res.code === 0) {
              this.dialogVisible = false
              this.queryPolicy()
              this.$store.dispatch('policyBrandOptions')
              this.$message({
              message: '新增成功',
              type: 'success',
              showClose: true
            })
            }
          }).catch(err => {
            this.$message({
              message: '新增失败',
              type: 'error',
              showClose: true
            })
          })
        },
        updatePolicy() {
          this.policy.brandId = parseInt(this.policy.brandId)
          if (Array.isArray(this.policy.saleArea)) {
            this.policy.saleArea = this.policy.saleArea.join(',')
          }
          if (Array.isArray(this.policy.ticketType)) {
            if (!this.policy.ticketType.includes(1)) {
              this.$message({
                message: '请选择开票方式',
                type: 'error'
              })
              return
            }
            this.policy.ticketType = this.policy.ticketType.join(',')
          } else {
            if (!this.policy.ticketType.includes(1)) {
              this.$message({
                message: '请选择开票方式',
                type: 'error'
              })
              return
            }
          }
          if (Array.isArray(this.policy.imgUrl) && this.policy.imgUrl.length > 1) {
            this.policy.imgUrl = this.policy.imgUrl.join(',')
          } else {
            if (this.policy.imgUrl.length > 0) {
              this.policy.imgUrl = (this.policy.imgUrl)[0]
            } else {
              this.policy.imgUrl = ''
            }
          }
           if (Array.isArray(this.policy.saleType)) {
            var saleTypeArr2 = this.policy.saleType
            if (!saleTypeArr2.includes(1)) {
              this.$message({
                message: '请选择销售方式',
                type: 'error'
              })
              return
            }
            if (saleTypeArr2[1] === 0) {
              this.policy.policyMargins = []
            }
            this.policy.saleType = this.policy.saleType.join(',')
          } else {
            if (!this.policy.saleType.includes(1)) {
              this.$message({
                message: '请选择销售方式',
                type: 'error'
              })
              return
            }
            var saleTypeStr2 = this.policy.saleType.split(',')
            if (saleTypeStr2[1] === '0') {
              this.policy.policyMargins = []
            }
          }
          // console.log(this.policy.imgUrl)
          // delete this.policy.number
          this.policy.policyMargins.forEach((item) => {
            delete item.readonly
          })
          if (this.policy.policyMargins.length !== 0) {
            this.policy.policyMargins.map((item) => {
              if (item.maxInterval !== '') {
                item.maxInterval = parseInt(item.maxInterval)
              }
              item.minInterval = parseInt(item.minInterval)
            })
          }
          api.policyUpdate(this.policy).then((res) => {
            if (+res.code === 0) {
              this.dialogEditVisible = false
              this.queryPolicy()
              this.$store.dispatch('policyBrandOptions')
              this.$message({
              message: '修改成功',
              type: 'success',
              showClose: true
            })
            }
          }).catch(err => {
            this.$message({
              message: '修改失败',
              type: 'error',
              showClose: true
            })
          })
        },
        handleClose(done) {
          this.dialogVisible = false
        },
        handleEditClose(done) {
          this.dialogEditVisible = false
        },
        // ======多选=====
        getSalesArea() {
          this.policy.saleArea = []
          this.policy.saleArea = [...this.salesArea1, ...this.salesArea2, ...this.salesArea3, ...this.salesArea4]
        },
        handleCheckAllChange1(val) {
          this.salesArea1 = val ? this.cityArr1 : []
          this.getSalesArea()
          this.isIndeterminate1 = false
        },
        handleCheckAllChange2(val) {
          this.salesArea2 = val ? this.cityArr2 : []
          this.getSalesArea()
          this.isIndeterminate2 = false
        },
        handleCheckAllChange3(val) {
          this.salesArea3 = val ? this.cityArr3 : []
          this.getSalesArea()
          this.isIndeterminate3 = false
        },
        handleCheckAllChange4(val) {
          this.salesArea4 = val ? this.cityArr4 : []
          this.getSalesArea()
          this.isIndeterminate4 = false
        },
        handleCheckedCitiesChange1(value) {
          const checkedCount = value.length
          this.checkAll1 = checkedCount === this.cityArr1.length
          this.isIndeterminate1 = checkedCount > 0 && checkedCount < this.cityArr1.length
          this.salesArea1 = value
          this.getSalesArea()
        },
        handleCheckedCitiesChange2(value) {
          const checkedCount = value.length
          this.checkAll2 = checkedCount === this.cityArr2.length
          this.isIndeterminate2 = checkedCount > 0 && checkedCount < this.cityArr2.length
          this.salesArea2 = value
          this.getSalesArea()
        },
        handleCheckedCitiesChange3(value) {
          const checkedCount = value.length
          this.checkAll3 = checkedCount === this.cityArr3.length
          this.isIndeterminate3 = checkedCount > 0 && checkedCount < this.cityArr3.length
          this.getSalesArea()
        },
        handleCheckedCitiesChange4(value) {
          const checkedCount = value.length
          this.checkAll4 = checkedCount === this.cityArr4.length
          this.isIndeterminate4 = checkedCount > 0 && checkedCount < this.cityArr4.length
          this.getSalesArea()
        },
      }
    }
  </script>
<style  lang="scss">
  .saleBusiness {
    position: relative;
    padding: 20px;
    .saleArea .el-form-item__label:before {
      content: '* ';
      color: red;
    }
    .el-table__row td .cell {
          overflow:hidden;
          text-overflow:ellipsis;
          white-space:nowrap;
          &:hover {
          display: block;
          width: 100%;
          overflow-y: auto;
          white-space: normal;
        }
    }
    .el-dialog {
      max-width: 1000px;
      overflow: hidden;
      .el-form {
        height: 450px;
        overflow-y: auto;
        overflow-x: hidden;
        margin-bottom: 20px;
      }
      .el-table--medium th {
        padding: 0 !important;
      }
      .el-checkbox + .el-checkbox {
        margin-left: 10px;
      }
      // .main {
      //   max-height: 450px;
      //   overflow-y: auto; 
      //   // overflow-x: hidden;
      //   margin-bottom: 20px;
      // }
      .minInterval {
        vertical-align: middle;
      }
    }
    .modalCheckBox {
        .el-checkbox-group {
          line-height: 18px;
          margin-left: 20px;
          margin-top: -5px;
          width: 600px;
          .el-checkbox {
            .el-checkbox__label {
              font-size: 12px;
              color: #666;
            }
          }
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  .left-container {
    background-color: #F38181;
    height: 100%;
  }

  .right-container {
    background-color: #FCE38A;
    height: 200px;
  }

  .top-container {
    background-color: #FCE38A;
    width: 100%;
    height: 100%;
  }

  .bottom-container {
    width: 100%;
    background-color: #95E1D3;
    height: 100%;
  }
</style>
